﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetfractionHub.Network.Protocol;
using NetfractionHub.Network.Protocol.BASE.Factory;

namespace NetfractionHub.LocalMachine.BotCommands.Handler
{
    [CommandHandler("getip", TriggerAlias="ip")]
    public class GetIPAddress : CommandHandler
    {
        public override BotReturnStatus HandleCommandMessage(NetfractionHub.RemoteMachine.Node source, CommandMessage message)
        {
            if (message.ArgumentsCount == 0)
            {
                if (Security.Permission.HasPermission(source.SecurityIdentity, typeof(Security.Permissions.GetOwnIpPermission)))
                    return new BotReturnStatus(true, string.Format("Your IP address is: {0}", 
                        source.Identity.IPv4Address != System.Net.IPAddress.None ? source.Identity.IPv4Address : source.Identity.IPv6Address));
                else
                    return new BotReturnStatus(false, Security.Permission.GetDeniedString(typeof(Security.Permissions.GetOwnIpPermission)));
            }
            else if (message.StringArguments.Count == 1 && message.StringArguments.ContainsKey("user") || message.UnnamedArguments.Count == 1)
            {
                string user = message.StringArguments.Count == 1 ? message.StringArguments["user"] : message.UnnamedArguments[0];
                if (Security.Permission.HasPermission(source.SecurityIdentity, typeof(Security.Permissions.GetIdentityIpPermission)))
                    return GetIdentityIPAddress(source, user);
                else
                    return new BotReturnStatus(false, Security.Permission.GetDeniedString(typeof(Security.Permissions.GetIdentityIpPermission)));
            }
            else
                return new BotReturnStatus(false);
        }

        private BotReturnStatus GetIdentityIPAddress(NetfractionHub.RemoteMachine.Node source, string user)
        {
            RemoteMachine.Node nodeToFind = Network.ConnectionManager.GetConnectedNodeByNickname(user);
            if (nodeToFind == null)
                return new BotReturnStatus(false, string.Format("Cannot get IP address, the user '{0}' does not exist.", user));

            return new BotReturnStatus(true, string.Format("{0} has the following IP address: {1}", nodeToFind.Identity.Nickname,
                nodeToFind.Identity.IPv4Address != System.Net.IPAddress.None ? nodeToFind.Identity.IPv4Address : nodeToFind.Identity.IPv6Address));
        }
    }
}
